﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Web;

namespace BLL.Unity
{
    public class RequestLifetimeManager : LifetimeManager
    {
        private Guid key;

        public RequestLifetimeManager() : this(Guid.NewGuid()) { }

        RequestLifetimeManager(Guid key)
        {
            if (key == Guid.Empty)
            {
                throw new ArgumentException("Key is empty");
            }
            this.key = key;
        }

        public override object GetValue()
        {
            object result = null;
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[key] != null)
                    result = HttpContext.Current.Items[key];
            }
            return result;
        }

        public override void RemoveValue()
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[key] != null)
                    HttpContext.Current.Items[key] = null;
            }
        }

        public override void SetValue(object newValue)
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[key] == null)
                {
                    HttpContext.Current.Items[key] = newValue;
                }
            }
        }
    }
}
